<template>
  <div class="container mx-auto px-4 py-8">
    <!-- 标题和添加按钮 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-900">区划管理</h1>
      <button @click="showAddModal = true" 
              class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
        添加区划
      </button>
    </div>

    <!-- 树形表格 -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">代码</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">级别</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <template v-for="region in displayRegions" :key="region.id">
            <tr class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                <div class="flex items-center">
                  <span :style="{ marginLeft: `${(region.level - 1) * 20}px` }" class="flex items-center">
                    <button v-if="region.level < 4"
                            @click="toggleNode(region)"
                            class="mr-2 w-4 text-gray-500 focus:outline-none">
                      <span v-if="loadingStates[region.code]">
                        <svg class="animate-spin h-4 w-4" viewBox="0 0 24 24">
                          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle>
                          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                      </span>
                      <span v-else>
                        {{ expandedNodes.has(region.code) ? '▼' : '▶' }}
                      </span>
                    </button>
                    <span v-else class="w-4 mr-2"></span>
                    {{ region.name }}
                  </span>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ region.code }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ region.level }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <button @click="editRegion(region)" 
                        class="text-blue-600 hover:text-blue-900 mr-3">
                  编辑
                </button>
                <button @click="deleteRegion(region)" 
                        class="text-red-600 hover:text-red-900">
                  删除
                </button>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑模态框 -->
    <div v-if="showAddModal || showEditModal" 
         class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center">
      <div class="bg-white rounded-lg p-8 max-w-md w-full">
        <h2 class="text-xl font-bold text-gray-900 mb-4">
          {{ showEditModal ? '编辑区划' : '添加区划' }}
        </h2>
        
        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700">名称</label>
            <input v-model="formData.name" 
                   type="text" 
                   required
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700">代码</label>
            <input v-model="formData.code" 
                   type="text" 
                   required
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700">上级代码</label>
            <input v-model="formData.parentCode" 
                   type="text"
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500">
          </div>

          <div class="flex justify-end space-x-3 mt-6">
            <button type="button" 
                    @click="closeModal"
                    class="px-4 py-2 text-gray-700 bg-gray-100 rounded hover:bg-gray-200">
              取消
            </button>
            <button type="submit"
                    class="px-4 py-2 text-white bg-blue-500 rounded hover:bg-blue-600">
              确定
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
const regions = ref(new Map()) // 使用 Map 存储所有加载的节点
const showAddModal = ref(false)
const showEditModal = ref(false)
const formData = ref({
  id: null,
  name: '',
  code: '',
  parentCode: ''
})
const expandedNodes = ref(new Set())
const loadingStates = ref({}) // 记录节点加载状态
const displayRegions = ref([]) // 当前显示的节点

// 初始加载一级节点
const fetchTopLevelRegions = async () => {
  try {
    const response = await $fetch('/api/regions', {
      params: {
        level: 1
      }
    })
    displayRegions.value = response.regions
    response.regions.forEach(region => {
      regions.value.set(region.code, region)
    })
  } catch (error) {
    console.error('获取一级区划失败:', error)
  }
}

// 加载子节点
const fetchChildren = async (parentCode) => {
  try {
    loadingStates.value[parentCode] = true
    const response = await $fetch('/api/regions', {
      params: {
        parentCode
      }
    })
    
    // 将新加载的子节点添加到 Map 中
    response.regions.forEach(region => {
      regions.value.set(region.code, region)
    })
    
    // 更新显示列表
    updateDisplayRegions()
    
  } catch (error) {
    console.error('获取子区划失败:', error)
  } finally {
    loadingStates.value[parentCode] = false
  }
}

// 切换节点展开状态
const toggleNode = async (region) => {
  const code = region.code
  
  if (expandedNodes.value.has(code)) {
    // 折叠节点
    expandedNodes.value.delete(code)
  } else {
    // 展开节点
    expandedNodes.value.add(code)
    // 如果还没有加载子节点，则加载
    if (!hasLoadedChildren(code)) {
      await fetchChildren(code)
    }
  }
  
  updateDisplayRegions()
}

// 检查是否已加载子节点
const hasLoadedChildren = (parentCode) => {
  return Array.from(regions.value.values()).some(r => r.parentCode === parentCode)
}

// 更新显示列表
const updateDisplayRegions = () => {
  const result = []
  
  // 添加一级节点
  const topLevel = Array.from(regions.value.values())
    .filter(r => r.level === 1)
    .sort((a, b) => a.code.localeCompare(b.code))
  
  for (const node of topLevel) {
    result.push(node)
    if (expandedNodes.value.has(node.code)) {
      addExpandedChildren(node.code, result)
    }
  }
  
  displayRegions.value = result
}

// 递归添加已展开的子节点
const addExpandedChildren = (parentCode, result) => {
  const children = Array.from(regions.value.values())
    .filter(r => r.parentCode === parentCode)
    .sort((a, b) => a.code.localeCompare(b.code))
  
  for (const child of children) {
    result.push(child)
    if (expandedNodes.value.has(child.code)) {
      addExpandedChildren(child.code, result)
    }
  }
}

// 获取区划列表
const fetchRegions = async () => {
  try {
    const response = await $fetch('/api/regions')
    regions.value = response.regions
  } catch (error) {
    console.error('获取区划列表失败:', error)
  }
}

// 创建区划
const createRegion = async () => {
  try {
    const level = Math.ceil(formData.value.code.length / 3)
    const response = await $fetch('/api/regions', {
      method: 'POST',
      body: { ...formData.value, level }
    })
    
    // 将新创建的节点添加到 Map 中
    const newRegion = response.region
    regions.value.set(newRegion.code, newRegion)
    
    // 如果有父节点，确保父节点是展开的
    if (newRegion.parentCode) {
      expandedNodes.value.add(newRegion.parentCode)
    }
    
    // 更新显示列表
    updateDisplayRegions()
    closeModal()
    alert('添加成功')
  } catch (error) {
    console.error('创建区划失败:', error)
    alert(error.data?.message || '创建失败')
  }
}

// 编辑区划
const editRegion = (region) => {
  formData.value = {
    id: region.id,
    name: region.name,
    code: region.code,
    parentCode: region.parentCode
  }
  showEditModal.value = true
}

// 更新区划
const updateRegion = async () => {
  try {
    const level = Math.ceil(formData.value.code.length / 3)
    const response = await $fetch(`/api/regions/${formData.value.id}`, {
      method: 'PUT',
      body: { ...formData.value, level }
    })
    
    // 更新 Map 中的节点数据
    const updatedRegion = response.region
    
    // 如果代码发生变化，需要删除旧的记录
    const oldRegion = Array.from(regions.value.values())
      .find(r => r.id === updatedRegion.id)
    if (oldRegion && oldRegion.code !== updatedRegion.code) {
      regions.value.delete(oldRegion.code)
    }
    
    // 更新或添加新记录
    regions.value.set(updatedRegion.code, updatedRegion)
    
    // 如果父节点变化，确保新的父节点是展开的
    if (updatedRegion.parentCode) {
      expandedNodes.value.add(updatedRegion.parentCode)
    }
    
    // 更新显示列表
    updateDisplayRegions()
    closeModal()
    alert('更新成功')
  } catch (error) {
    console.error('更新区划失败:', error)
    alert(error.data?.message || '更新失败')
  }
}

// 删除区划
const deleteRegion = async (region) => {
  // 添加确认提示
  if (!confirm(`确定要删除"${region.name}"吗？删除后其下级区划也会被删除！`)) {
    return
  }
  
  try {
    await $fetch(`/api/regions/${region.id}`, {
      method: 'DELETE'
    })
    
    // 从 Map 中移除被删除的节点及其子节点
    const removeNodeAndChildren = (code) => {
      const children = Array.from(regions.value.values())
        .filter(r => r.parentCode === code)
      
      // 递归删除子节点
      children.forEach(child => {
        removeNodeAndChildren(child.code)
      })
      
      // 删除当前节点
      regions.value.delete(code)
      // 从展开集合中移除
      expandedNodes.value.delete(code)
    }
    
    removeNodeAndChildren(region.code)
    
    // 更新显示列表
    updateDisplayRegions()
    
    // 添加成功提示
    alert('删除成功')
  } catch (error) {
    console.error('删除区划失败:', error)
    alert(error.data?.message || '删除失败')
  }
}

// 关闭模态框
const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = {
    id: null,
    name: '',
    code: '',
    parentCode: ''
  }
}

// 处理表单提交
const handleSubmit = async () => {
  if (showEditModal.value) {
    await updateRegion()
  } else {
    await createRegion()
  }
}

// 初始化加载
onMounted(() => {
  fetchTopLevelRegions()
})
</script>

<style scoped>
.tree-node {
  display: flex;
  align-items: center;
}

.tree-indent {
  display: inline-block;
  width: 20px;
}
</style> 